<?php
/**
 * Created by PhpStorm.
 * User: Apache
 *  1 展会活动 2 环节
 *
 */

namespace app\api\controller\activemanage;
use app\api\controller\common\ApiBase;
use think\Db;
use think\Model;
use app\api\model\Admin as AdminModel;
use app\api\controller\common\CommonPlus;
use think\Controller; // dengh quxiao
// Controller  ApiBase （dengl）
class Zhactiveweb extends Controller
{

    protected $admin;
    protected $model = null;
    public function _initialize()
    {
        parent::_initialize();
        $this->admin = session('admin');
        //$this->model = model('CompanyPublic');
    }


    /**
     * 根据公海id获得获取
     * @return \think\response\Json|void
     *  http://dxshowxya.for.pub/index.php?s=/api/basemanage/Yuyuemanage/getList
     */

    public function getTabName($exhibition_id){
        $result=db('exhibition')->where(['id'=>$exhibition_id])->find();
        $tabName='';
        if($result){
            $tabName=$result['create_person_table'];
        }else{
            return json(['code'=>0,'msg'=>'缺少关键字段','data'=>'']);
        }
        return $tabName;
    }

    /**
     *
     * @return \think\response\Json|void
     *  comppub
     *  获取活动详情及环节列表
     */

    public function getActiveList(){
        $id = $this->request->param('id');
        $res=db('zh_active')->where(['id'=>$id,'is_del'=>0])->find();
        return json(['code'=>1,'msg'=>'success','data'=>$res]);
    }


    //添加报名
    public function addActive(){
        if (request()->isPost()) {
            Db::startTrans();
            try {
                $active_id = $this->request->param('active_id');
                $res=db('zh_active')->where(['id'=>$active_id,'is_del'=>0,'status_show'=>0])->find();
                if(!$res){
                    return json(['code'=>0,'msg'=>'活动数据错误']);
                }
                $mobile_person = $this->request->param('mobile_person');
                if(empty($mobile_person)){
                    return json(['code'=>0,'msg'=>'请填写电话']);
                }
                $exhibition_id = $this->request->param('exhibition_id');
                $exhibition=db('exhibition')->where(['is_delete'=>0,'id'=>$exhibition_id])->find();
                if(!$exhibition){
                    return json(['code'=>0,'msg'=>'展会信息错误']);
                }

                $resMobile=db('zh_active_signup')->where(['mobile_person'=>$mobile_person,'is_delete'=>0,'active_id'=>$active_id])->find();
                if($resMobile){
                    return json(['code'=>0,'msg'=>'此电话已报名']);
                }
                $name_cn = $this->request->param('name_cn');
                if(empty($name_cn)){
                    return json(['code'=>0,'msg'=>'请填写姓名']);
                }
                $id_side = $this->request->param('id_side');
                if(empty($id_side)){
                    return json(['code'=>0,'msg'=>'请填写证件号码']);
                }
                $id_positive=$this->request->param('id_positive');
                if(empty($id_positive)){
                    return json(['code'=>0,'msg'=>'请填写证件类型']);
                }
                if($id_positive == '中国居民身份证'){
                    $nameOrId=$this->getUserId($name_cn,$id_side);
                    if($nameOrId['code']==0){
                        return json(['code'=>0,'msg'=>'身份证：'.$nameOrId['msg']]);
                    }
                }
                $company_name = $this->request->param('company_name');
                if(empty($company_name)){
                    return json(['code'=>0,'msg'=>'请填写公司名称']);
                }
                $department_cn = $this->request->param('department_cn');
                if(empty($department_cn)){
                    return json(['code'=>0,'msg'=>'请填写部门信息']);
                }
                $positions_cn = $this->request->param('positions_cn');
                if(empty($positions_cn)){
                    return json(['code'=>0,'msg'=>'请填写职位信息']);
                }
                $email = $this->request->param('email');
                if(empty($email)){
                    return json(['code'=>0,'msg'=>'请填写电子邮件']);
                }
                $telCode = $this->request->param('code');
                $resCode=db('phone_code')->where(['phone'=>$mobile_person])->find();
                if(!$resCode){
                    return json(['code'=>0,'msg'=>'短信验证码错误,请重新发送']);
                }
                if($telCode!==$resCode['code']){
                    return json(['code'=>0,'msg'=>'短信验证码错误,请重新发送']);
                }
                if ($resCode['time'] < time()) {
                    return json(['code'=>0,'msg'=>'短信验证码已过期']);
                }
                $is_pc=$this->request->param('is_pc');
                $channel_id=$this->request->param('channel_id');
                $group_invitation_type=$this->request->param('group_invitation_type');
                $group_invitation_type=$group_invitation_type?$group_invitation_type:1;
                //开始事务
                //基础表填入
                $data['name_cn']=$name_cn;
                $data['company_name']=$company_name;
                $data['department_cn']=$department_cn;
                $data['email']=$email;
                $data['update_time']=time();
                $data['create_time']=time();
                $data['positions_cn']=$positions_cn;
                $data['mobile_person']=$mobile_person;
                $baseInfo=db('company_user')->where(['mobile_person'=>$mobile_person])->find();
                $baseId=false;
                if(!$baseInfo){
                    $baseId = db('company_user')->lock(true)->insertGetId($data);
                }else{
                    $baseId=$baseInfo['id'];
                }
                if(false === $baseId){
                    Db::rollback();
                    return json(array('code' => '0', 'msg' => '操作失败'));
                }
                //加入到观众列表
                $tabName=$this->getTabName($exhibition_id);
                $personInfo=db($tabName)->where(['person_id'=>$baseId])->find();
                $personRes=true;
                if(!$personInfo){
                    $max_id = db($tabName)->max('id');
                    $is_cart= $is_pc == 1?415000000:311000000;
                    $data['person_id']=$baseId;
                    $data['id_side']=$id_side;
                    $data['id_positive']=$id_positive;
                    $data['is_beforehand']=2;
                    $data['is_cart']=$is_cart+$max_id+1;
                    $data['channel_id']=$channel_id;
                    $data['status']=4;
                    $data['group_invitation_type']=$group_invitation_type;
                    if($group_invitation_type == 2){
                        $data['examine_type']=1;
                    }
                    $personRes = db($tabName)->lock(true)->insert($data);
                }else{
                    $updates['name_cn']=$name_cn;
                    $updates['id_side']=$id_side;
                    $updates['id_positive']=$id_positive;
                    $data['id_side']=$id_side;
                    $data['id_positive']=$id_positive;
                    if(!$personInfo['id_side'] || !$personInfo['id_positive']){
                        $personRes = db($tabName)->where(['id'=>$personInfo['id']])->update($updates);
                    }
                }
                if(false === $personRes){
                    Db::rollback();
                    return json(array('code' => '0', 'msg' => '操作失败'));
                }
                if(array_key_exists("person_id",$data)){unset($data['person_id']);}
                if(array_key_exists("is_beforehand",$data)){unset($data['is_beforehand']);}
                if(array_key_exists("is_cart",$data)){unset($data['is_cart']);}
                if(array_key_exists("status",$data)){unset($data['status']);}
                if(array_key_exists("group_invitation_type",$data)){unset($data['group_invitation_type']);}
                if(array_key_exists("examine_type",$data)){unset($data['examine_type']);}
                $data['channel_id']=$channel_id;
                $data['signup_type']=$this->request->param('signup_type');
                $data['signup_type']=$data['signup_type']?$data['signup_type']:0;
                $data['product']=$this->request->param('product');
                $data['ong_advantage']=$this->request->param('ong_advantage');
                $data['sales_volume']=$this->request->param('sales_volume');
                $data['qualifications']=$this->request->param('qualifications');
                $data['major_exporting_countries']=$this->request->param('major_exporting_countries');
                $data['cooperative_enterprise']=$this->request->param('cooperative_enterprise');
                $data['active_type']=$this->request->param('active_type');
                $data['join_active_type']=$this->request->param('join_active_type');
                $data['zy_class']=$this->request->param('zy_class');
                $data['industry']=$this->request->param('industry');
                $data['stores_number']=$this->request->param('stores_number');
                $data['purchase']=$this->request->param('purchase');
                $data['zy_management']=$this->request->param('zy_management');
                $sex=$this->request->param('sex');
                $data['sex']=$sex?$sex:'男';
                $data['active_id']=$active_id;
                $data['email']=$email;
                $data['exhibition_id']=$exhibition_id;
                $result=db('zh_active_signup')->lock(true)->insert($data);
                if(false === $result){
                    return json(['code'=>0,'msg'=>'操作失败']);
                }
                Db::commit();
                return json(array('code' => '1', 'msg' => '成功'));
            } catch (\Exception $e) {
                Db::rollback();
                return json(array('code' => '0', 'msg' => $e->getMessage()));
            }
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }



    public function getUserId($user_name,$user_id){
        $host = "https://eid.shumaidata.com";
        $path = "/eid/check";
        $method = "POST";
        $appcode = "46e8328cca644eb4bbf844f8538bd714";
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        $querys = "idcard=".$user_id."&name=".$user_name;
        $bodys = "";
        $url = $host . $path . "?" . $querys;

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        //设定返回信息中是否包含响应信息头，启用时会将头文件的信息作为数据流输出，true 表示输出信息头, false表示不输出信息头
        //如果需要将字符串转成json，请将 CURLOPT_HEADER 设置成 false
        curl_setopt($curl, CURLOPT_HEADER, false);
        if (1 == strpos("$".$host, "https://"))
        {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        $result=curl_exec($curl);
        if($result){
            $result=json_decode($result,true);
            if($result['code']=='0'){
                if($result['result']['res'] == 1){
                    return array('code'=>1,'msg'=>'验证正确');
                }else{
                    return array('code'=>0,'msg'=>$result['result']['description']);
                }
            }else{
                return array('code'=>0,'msg'=>$result['message']);
            }
        }else{
            return array('code'=>0,'msg'=>'请求失败');
        }
    }


    // 活动列表
    public function getList(){
        $page = $this->request->param('page');
        $page = max(1,intval($page));
        $pagesize =$this->request->param('pageSize')==""?20:$this->request->param('pageSize');
        $exhibition_id = $this->request->param('exhibition_id');
        $exhibition=db('exhibition')->where(['is_delete'=>0,'id'=>$exhibition_id])->find();
        if(!$exhibition){
            return json(['code'=>0,'msg'=>'展会信息错误']);
        }
        $type_hdlb =$this->request->param('type_hdlb');
        $param=" and m.is_del=0 and m.status_show=0 ";
        if(!empty($exhibition_id)){
            $param.=" and m.exhibition_id=$exhibition_id ";
        }
        if(!empty($type_hdlb)){
            $param.=" and (m.type_hdlb like '%$type_hdlb%') ";
        }
        $keyword =input('keyword');
        if (!empty($keyword)) {
            $param.=" and (m.title like '%$keyword%') ";
        }
        $param.=" order by m.id desc";
        $sql2="select m.*,e.title as exhibition_name";
        $sql2.=" from crm_zh_active m ";
        $sql2.=" left join crm_exhibition as e on e.id=m.exhibition_id";
        $sql2.=" where 1=1 $param";
        $total1=Db::query($sql2);
        $sql2.=" limit ".($page-1)*$pagesize.",$pagesize";
        $list=Db::query($sql2);
        $total=count($total1); //st
        return json(['code'=>1,'msg'=>'success','data'=>['list'=>$list,'count'=>$total]]);
    }



    //开票管理
    public function addOrEdit(){
        if (request()->isPost()) {
            $active_id = isset($post['active_id']) && $post['active_id'] != '' ? $post['active_id'] : 0;
            $active=db('zh_active')->where(['id'=>$active_id,'is_del'=>0,'status_show'=>0])->find();
            if(!$active){
                return json(array('code' => '0', 'msg' => '活动数据错误'));
            }
            $signup_id=isset($post['signup_id']) && $post['signup_id'] != '' ? $post['signup_id'] : 0;
            $signUp=db('zh_active_signup')->where(['id'=>$signup_id,'is_delete'=>0,'play_status'=>0])->find();
            if(!$signUp){
                return json(array('code' => '0', 'msg' => '报名数据错误'));
            }
            $exhibition_id = isset($post['exhibition_id']) && $post['exhibition_id'] != '' ? $post['exhibition_id'] : null;
            $company_id = isset($post['company_id']) && $post['company_id'] != '' ? $post['company_id'] : null;
            $id = isset($post['id']) && $post['id'] != '' ? $post['id'] : null;
            $billing_type = isset($post['billing_type']) && $post['billing_type'] != '' ? $post['billing_type'] : 1;
            $tax_number = isset($post['tax_number']) && $post['tax_number'] != '' ? $post['tax_number'] : '';
            $bank_title = isset($post['bank_title']) && $post['bank_title'] != '' ? $post['bank_title'] : '';
            $bank_number = isset($post['bank_number']) && $post['bank_number'] != '' ? $post['bank_number'] : '';
            $company_phone = isset($post['company_phone']) && $post['company_phone'] != '' ? $post['company_phone'] : '';
            $company_address = isset($post['company_address']) && $post['company_address'] != '' ? $post['company_address'] : '';
            $billing_mode = isset($post['billing_mode']) && $post['billing_mode'] != '' ? $post['billing_mode'] : 1;
            $billing_money = isset($post['billing_money']) && $post['billing_money'] != '' ? $post['billing_money'] : '';
            $receiving_name = isset($post['receiving_name']) && $post['receiving_name'] != '' ? $post['receiving_name'] : '';
            $receiving_phone = isset($post['receiving_phone']) && $post['receiving_phone'] != '' ? $post['receiving_phone'] : '';
            $receiving_address = isset($post['receiving_address']) && $post['receiving_address'] != '' ? $post['receiving_address'] : '';
            $data['active_id']=$active_id;
            $data['exhibition_id']=$exhibition_id;
            $data['company_id']=$company_id;
            $data['billing_type']=$billing_type;
            $data['tax_number']=$tax_number;
            $data['bank_title']=$bank_title;
            $data['bank_number']=$bank_number;
            $data['company_phone']=$company_phone;
            $data['company_address']=$company_address;
            $data['billing_mode']=$billing_mode;
            $data['billing_money']=$billing_money;
            $data['receiving_name']=$receiving_name;
            $data['receiving_phone']=$receiving_phone;
            $data['receiving_address']=$receiving_address;
            $data['signup_id']=$signup_id;
            $data['create_time']=time();
            $data['update_time']=time();
            $res='';
            if($id){
                $search=db('billing')->where(['id'=>$id])->find();
                if(!$search){
                    return json(array('code' => '0', 'msg' => '数据错误'));
                }
                $res=db('billing')->where(['id'=>$id])->update($data);
            }else{
                $res=db('billing')->insert($data);
            }

            if(!$res){
                return json(array('code' => '0', 'msg' => '操作失败'));
            }
            return json(array('code' => '1', 'msg' => '操作成功'));
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }


    public function getExhibition(){
        $exhibition_id = $this->request->param('exhibition_id');
        $exhibition=db('exhibition')->where(['is_delete'=>0,'id'=>$exhibition_id])->find();
        if(!$exhibition){
            return json(['code'=>0,'msg'=>'展会信息错误']);
        }
        return json(['code'=>1,'msg'=>'成功','data'=>$exhibition]);
    }



    public function delPhone(){
        $phone = $this->request->param('phone');
        $resMobile=db('zh_active_signup')->where(['mobile_person'=>$phone,'is_delete'=>0])->select();
        if(!$resMobile){
            return json(['code'=>0,'msg'=>'未找到电话']);
        }
        foreach ($resMobile as &$vv){
            db('zh_active_signup')->where('id',$vv['id'])->delete();
        }

        return json(['code'=>1,'msg'=>'删除成功']);
    }



    //获取推荐人渠道
    public function getChannel(){
        $exhibition_id = $this->request->param('exhibition_id');
        $exhibition=db('exhibition')->where(['is_delete'=>0,'id'=>$exhibition_id])->find();
        if(!$exhibition){
            return json(['code'=>0,'msg'=>'展会信息错误']);
        }
        //观众邀请
        $channel=db('active_zsqudao')->where(['title'=>'官网','is_delete'=>0])->find();
        if($channel){
            return json(['code'=>1,'msg'=>'操作成功','data'=>$channel]);
        }else{
            $channel=$this->addChannel($exhibition);
            return json($channel);
        }
    }

    public function addChannel($exhibition){
        $data['exhibition_id'] = $exhibition['id'];
        $data['type']='官网';   // 中文
        $data['number']='01';   // 中文
        $data['position']='官网进入';   // 中文
        $data['title']='官网';   // 中文
        $data['create_time']=time();   // 中文
        $data['update_time']=time();   // 中文crm_zsqudao
        $id = db('active_zsqudao')->insertGetId($data);
        if(!$id){
            return array('code'=>0,'msg'=>'获取渠道失败');
        }
        $data['id']=$id;
        return array('code'=>1,'msg'=>'成功','data'=>$data);
    }



    /**
     * 活动中心
     *
     * @return void
     */
    public function articleMenuDetail()
    {
        if (request()->isPost()) {
            $post = input('post.');
            $exhibition_id = $this->request->param('exhibition_id');
            $exhibition=db('exhibition')->where(['is_delete'=>0,'id'=>$exhibition_id])->find();
            if(!$exhibition){
                return json(['code'=>0,'msg'=>'展会信息错误']);
            }
            $id = isset($post['id']) && $post['id'] != '' ? $post['id'] : 0;
            $activeList=db('zh_active')->where(['is_del'=>0,'exhibition_id'=>$exhibition_id])->limit('1,4')->select();
            $detail=db('zh_active')->where(['is_del'=>0,'id'=>$id])->find();
            $sqlPer="select * from crm_zh_active where id = (select id from crm_zh_active where id < ".$id." and exhibition_id=".$exhibition_id." and is_del=0 order by id desc limit 1)"; //上一条记录
            $resPre=Db::query($sqlPer);
            $sqlNext="select * from crm_zh_active where id = (select id from crm_zh_active where id > ".$id." and exhibition_id=".$exhibition_id." and is_del=0 order by id asc limit 1)"; //下一条记录
            $resNext=Db::query($sqlNext);
            return json(['code'=>1,'msg'=>'success','activeList'=>$activeList,'detail'=>$detail,'perData'=>$resPre,'nextData'=>$resNext]);
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }

}
